package org.solr;

import java.io.IOException;
import java.net.MalformedURLException;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.zookeeper.Op.Delete;

public class DeleteIndex {
	static String Base_URL = "http://localhost:8983/solr/collection1";
	static String zkHost = "localhost:2181";
	static String defaultCollection = "collection1";
	static int zkClientTimeout = 60000;
	static int zkConnectTimeout = 5000;
	static CloudSolrServer solrServer;

	private void init() {
		try {
			solrServer = new CloudSolrServer(zkHost);
			solrServer.setDefaultCollection(defaultCollection);
			solrServer.setZkClientTimeout(zkClientTimeout);
			solrServer.setZkConnectTimeout(zkConnectTimeout);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void search() {
		try {
			SolrQuery query = new SolrQuery();
			query.setQuery("*:*");
			query.addSortField("_version_", SolrQuery.ORDER.asc);
			QueryResponse rsp = solrServer.query(query);			
			SolrDocumentList docs = rsp.getResults();
			System.out.println("文档个数：" + docs.getNumFound());
			System.out.println("查询时间：" + rsp.getQTime());
			for (SolrDocument doc : docs) {
				for (String FieldNames : doc.getFieldNames()) {
					System.out.println(FieldNames + ":"
							+ doc.getFieldValue(FieldNames));
				}
			}

		} catch (SolrServerException e) {
			e.printStackTrace();
		}
	}
	
	private void doDelete() {
		try {
//			solrServer.deleteById("0");
			solrServer.deleteByQuery("id:0");
			solrServer.commit();
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		DeleteIndex deleteIndex = new DeleteIndex();
		deleteIndex.init();
		deleteIndex.search();
		deleteIndex.doDelete();
	}
}
